package com.drinks.yiniang.ui.activity.user.order;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.StyleSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.user.order.OrdePayResultAdapter;
import com.drinks.yiniang.common.recycler.decoration.PayResultGoodsItemDecoration;
import com.drinks.yiniang.entity.goods.GoodsJson;
import com.drinks.yiniang.entity.goods.RecommendGoodsJson;
import com.drinks.yiniang.entity.user.order.OrderEvaluateJson;
import com.drinks.yiniang.io.api.GoodsApiIO;
import com.drinks.yiniang.io.api.OrderApiIO;
import com.drinks.yiniang.io.api.ShoppingCartApiIO;
import com.drinks.yiniang.ui.activity.goods.GoodsDetailsActivity;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.utils.RecyclerUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.ColorUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;

public class OrderPayResultActivity extends BaseTranBarActivity implements OnNavgationBarClickListener,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    //nav
    private NavigationBarLayout nav_bar_order_pay_result;
    private BaseRecyclerView rcv_order_pay_result;
    //header view
    private View mHeaderView;
    //支付状态
    private TextView tv_order_pay_status;
    //返回
    private Button btn_order_pay_result_back;
    //查看订单
    private Button btn_order_pay_result_check;
    //支付tips
    private TextView tv_order_pay_tips;

    private OrdePayResultAdapter mOrdePayResultAdapter;

    //订单编号
    //private String mOrdeNo;
    //获得积分
    //订单id
    //private String mOrderId;
    private String mGainPoints;
    //当前支付方式
    //private int mCurrentPayType;
    //是否支付成功
    private boolean isPaySuccess;
    //支付错误信息
    private String mPayFailInfo;

    @Override
    protected void initView() {
        nav_bar_order_pay_result = findViewById(R.id.nav_bar_order_pay_result);

        rcv_order_pay_result = findViewById(R.id.rcv_order_pay_result);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        if (getIntent() != null) {
            isPaySuccess = getIntent().getBooleanExtra(Constants.KeyBoolen, false);
            mGainPoints = getIntent().getStringExtra(Constants.KeyTotal);
            mPayFailInfo = getIntent().getStringExtra(Constants.KeyTextContents);
            //mOrderId = getIntent().getStringExtra(Constants.KeyOrderId);
        }

        initAdapter();
        switchPayResult();
        getRecommend();
    }

    private void initAdapter() {
        mOrdePayResultAdapter = new OrdePayResultAdapter(mContext, new ArrayList<GoodsJson.GoodsList>());
        mOrdePayResultAdapter.addHeaderView(getHeaderView());
        mOrdePayResultAdapter.setHeaderAndEmpty(true);
        mOrdePayResultAdapter.setCenterEmpty(getLayoutInflater(), rcv_order_pay_result);
        mOrdePayResultAdapter.bindToRecyclerView(rcv_order_pay_result);

        rcv_order_pay_result.addItemDecoration(PayResultGoodsItemDecoration.getItemDPDecoration(10));
        rcv_order_pay_result.setLayoutManager(RecyclerUtils.getPayResultGoodsGridLayout(mContext));
    }

    //获取header
    private View getHeaderView() {
        mHeaderView = getLayoutInflater().inflate(R.layout.header_order_pay_result, (ViewGroup) rcv_order_pay_result.getParent(), false);

        tv_order_pay_status = mHeaderView.findViewById(R.id.tv_order_pay_status);
        tv_order_pay_tips = mHeaderView.findViewById(R.id.tv_order_pay_tips);

        btn_order_pay_result_back = mHeaderView.findViewById(R.id.btn_order_pay_result_back);
        btn_order_pay_result_check = mHeaderView.findViewById(R.id.btn_order_pay_result_check);


        btn_order_pay_result_back.setOnClickListener(this);
        btn_order_pay_result_check.setOnClickListener(this);

        return mHeaderView;
    }

    @Override
    protected void initListener() {
        nav_bar_order_pay_result.setOnNavgationBarClickListener(this);
        btn_order_pay_result_back.setOnClickListener(this);
        btn_order_pay_result_check.setOnClickListener(this);
        mOrdePayResultAdapter.setOnItemClickListener(this);
        mOrdePayResultAdapter.setOnItemChildClickListener(this);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.btn_order_pay_result_back://返回商品
                finish();
                break;
            case R.id.btn_order_pay_result_check://查看订单
//                Intent intent = new Intent(mContext, OrderDetailsActivity.class);
//                intent.putExtra(Constants.KeyOrderId, mOrderId);
//                intent.putExtra(Constants.KeyStatus, isPaySuccess ? "1" : "0");
//                startActivity(intent);
                Intent intent = new Intent(mContext, MyOrderActivity.class);
                intent.putExtra(Constants.KeyOrderType, isPaySuccess ? Constants.TYPE_ORDER_WAIT_FOR_DELIVER : Constants.TYPE_ORDER_WAIT_FOR_PAY);
                startActivity(intent);

                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_order_pay_result;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        GoodsJson.GoodsList data = mOrdePayResultAdapter.getItem(position);

        if (data == null) {
            return;
        }

        Intent intent = new Intent(mContext, GoodsDetailsActivity.class);
        intent.putExtra(Constants.KeyGoodsId, data.getId());
        startActivity(intent);
    }

    private void switchPayResult() {
        if (isPaySuccess) {//支付成功
            nav_bar_order_pay_result.setBackgroundResource(R.drawable.shape_bkg_header_order_pay_result);
            mHeaderView.setBackgroundResource(R.drawable.shape_bkg_header_order_pay_result);

            tv_order_pay_status.setTextColor(Color.WHITE);
            tv_order_pay_status.setText(R.string.text_pay_success);
            tv_order_pay_status.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_pay_success, 0, 0, 0);

            tv_order_pay_tips.setText(String.format(getString(R.string.text_pay_get_points), StringUtils.getNullEmptyConvertZero(mGainPoints)));
            tv_order_pay_tips.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_pay_get_points, 0, 0, 0);
            tv_order_pay_tips.setBackgroundResource(R.drawable.shape_bkg_round5_white);

            btn_order_pay_result_back.setTextColor(Color.WHITE);
            btn_order_pay_result_check.setTextColor(Color.WHITE);

            btn_order_pay_result_back.setBackgroundResource(R.drawable.shape_border_round25_white);
            btn_order_pay_result_check.setBackgroundResource(R.drawable.shape_border_round25_white);
        } else {
            SpannableStringBuilder builder = new SpannableStringBuilder();

            nav_bar_order_pay_result.setBackgroundColor(Color.WHITE);
            mHeaderView.setBackgroundColor(Color.WHITE);

            tv_order_pay_status.setTextColor(ColorUtils.getColorById(mContext, R.color.color_main));
            tv_order_pay_status.setText(R.string.text_pay_fail);
            tv_order_pay_status.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_pay_fail, 0, 0, 0);

            builder.append(getString(R.string.text_fail_reason_colon));
            int end = builder.length();
            builder.append(mPayFailInfo);
            builder.setSpan(new StyleSpan(Typeface.BOLD), 0, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

            tv_order_pay_tips.setText(builder);
            tv_order_pay_tips.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            tv_order_pay_tips.setBackgroundResource(R.drawable.shape_bkg_round5_f2f2f2);

            btn_order_pay_result_back.setTextColor(ColorUtils.getColorById(mContext, R.color.color_282829));
            btn_order_pay_result_check.setTextColor(ColorUtils.getColorById(mContext, R.color.color_282829));

            btn_order_pay_result_back.setBackgroundResource(R.drawable.shape_border_round25_b4b4b4);
            btn_order_pay_result_check.setBackgroundResource(R.drawable.shape_border_round25_b4b4b4);
        }
    }

    //获取推荐列表
    private void getRecommend() {
        GoodsApiIO.getInstance().getRecommendGoodsList(new APIRequestCallback<RecommendGoodsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(RecommendGoodsJson res) {
                if (mOrdePayResultAdapter == null) {
                    return;
                }

                mOrdePayResultAdapter.getData().clear();
                mOrdePayResultAdapter.addData(res.getData());
                mOrdePayResultAdapter.loadMoreEnd();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                mOrdePayResultAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    //获取支付结果
    private void getOrderPayResult() {
        showLoadingDialog();

        OrderApiIO.getInstance().getOrderPayResult("", 0, new APIRequestCallback<OrderEvaluateJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(OrderEvaluateJson res) {
                switchPayResult();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        GoodsJson.GoodsList data = mOrdePayResultAdapter.getItem(position);

        if(data != null && view.getId() == R.id.iv_home_goods_add_cart) {
            addToCart(data.getId());
        }
    }

    private void addToCart(String goodsId) {
        showLoadingDialog();

        ShoppingCartApiIO.getInstance().addToShopCart(goodsId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                ToastUtils.showShort(getString(R.string.text_add_success));
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }
}
